package com.xuchao.yao_jz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.xuchao.yao_jz.config.PayConfig;
import com.xuchao.yao_jz.service.AlibabaPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AlibabaPayServiceImpl implements AlibabaPayService {

    @Autowired
    PayConfig payConfig;
    @Autowired
    StringRedisTemplate StringRedisTemplate;

    @Override
    public AlipayTradePrecreateResponse createQrCodePayOrder(Map<String, String> map) throws AlipayApiException {
        //构造client
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl(payConfig.getUrl());
        //设置应用Id
        certAlipayRequest.setAppId(payConfig.getAppid());
        //设置应用私钥
        certAlipayRequest.setPrivateKey(payConfig.getPrivateKey());
        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset("utf-8");
        //设置签名类型
        certAlipayRequest.setSignType("RSA2");
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(payConfig.getAppCertPath());
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(payConfig.getAlipayCertPath());
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(payConfig.getAlipayRootCertPath());
        //构造client
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        //构造API请求
//        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();//创建API对应的request类
        request.setNotifyUrl(payConfig.getCallBackUrl());
        request.setBizContent(JSON.toJSONString(map));//订单允许的最晚付款时间
        //发送请求
        AlipayTradePrecreateResponse alipayTradePrecreateResponse = alipayClient.certificateExecute(request);
        log.info("请求支付宝返回的结果为:{}",alipayTradePrecreateResponse.getBody());
        return alipayTradePrecreateResponse;
    }

    @Override
    public String getAlibabaPayQRCode(AlipayTradePrecreateResponse qrCodePayOrder) {
        log.info("---------------------------qrCodePayOrder:{}----------------------------",JSON.toJSONString(qrCodePayOrder));
        StringRedisTemplate.opsForValue().set(qrCodePayOrder.getOutTradeNo(),qrCodePayOrder.getQrCode(),3600, TimeUnit.SECONDS);
        return StringRedisTemplate.opsForValue().get(qrCodePayOrder.getOutTradeNo());
    }
}
